using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using AutoGear.BLL;
using ECommerce.Library.DataStructure;
using System.Collections.Generic;
using ECommerce.Library;
using System.IO;
using ECommerce.Library.ECommerce;
using Entity;
using eShop.Model;
using eShop.DataAccess;
using eShop.Business;

public partial class admin_product_add : SiteAdminBasePage
{
    private ECommerce.DAL.CustomCollection<ProductPartner> partnerProducts
    {
        get
        {
            
            return HttpContext.Current.Session["_partnerProducts"] as ECommerce.DAL.CustomCollection<ProductPartner>;
        }
        set
        {
            HttpContext.Current.Session["_partnerProducts"] = value;
        }
    }

    private ECommerce.DAL.CustomCollection<Manufacturer> brands
    {
        get
        {
            return HttpContext.Current.Session["_brands"] as ECommerce.DAL.CustomCollection<Manufacturer>;
        }
        set
        {
            HttpContext.Current.Session["_brands"] = value;
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            LoadDropDowns();
            AutoGearSessionManager.ClearTemporaryStock();
            LoadPartners();
        }
    }

    private void LoadPartners()
    {
        brands = ManufacturerManager.Brands(true);
        brands.Add(new Manufacturer(-1, "Select", "", "", "", true, string.Empty));
        ECommerce.DAL.CustomCollection<ProductPartner> partProd = new ECommerce.DAL.CustomCollection<ProductPartner>();
        partnerProducts = partProd;
    }

    protected void Create_Click(object sender, EventArgs e)
    {
        try
        {
            if (IsValid)
            {
                string name = tbxProductName.Text;
                string name2 = tbxProductName2.Text;
                string categoryId = ddlParent.SelectedValue;
                //string brandId = ddlBrand.SelectedValue;
                string displayOrder = tbxDisplayOrder.Text;
                string price = tbxPrice.Text;
                double retailprice = Security.BindDoubleInput(tbxRetailPrice.Text, SecurityLevel.Zero);
                string itemNumber = tbxItemNumber.Text;
                bool featuredListing = cbxFeatured.Checked;
                bool active = cbxIsActive.Checked;
                bool decimalSize = false;
                string description = hidDescription.Value.Trim(); ;
                double weight = Security.BindDoubleInput(tbxWeight.Text, SecurityLevel.Zero);
                double weightoz = Security.BindDoubleInput(tbxWeightUnit.Text, SecurityLevel.Zero);
                int stockAmount = Security.BindIntegerInput(tbxStock.Text, SecurityLevel.Zero);
                double currentCost = Security.BindDoubleInput(tbxCurrentCost.Text, SecurityLevel.Zero);
                double additionalPrice = Security.BindDoubleInput(tbxAdditionalPrice.Text, SecurityLevel.Zero);
                double standardCost = Security.BindDoubleInput(tbxStandardCost.Text, SecurityLevel.Zero);
                string recipies=hidRecipies.Value.Trim();
                string additionalinfo =hidAdditionalInfo.Value.Trim();
                int pkgQuanity = Security.BindIntegerInput(tbxPkgQuanity.Text, SecurityLevel.Zero);

                string tempImageFolder = UploadTemporaryFiles();

                string size = Security.BindStringInput(tbxSize.Text, SecurityLevel.Zero);
                string weightUnit = string.Empty;

                int widthWholeNumberFirstDigit = Security.BindIntegerInput(tbxWidthWholeFirstDigit.Text, SecurityLevel.Zero);
                int widthWholeNumberSecondDigit = Security.BindIntegerInput(tbxWidthWholeSecondDigit.Text, SecurityLevel.Zero);
                int widthFractionNumberFirstDigit = Security.BindIntegerInput(tbxWidthFractionFirstDigit.Text, SecurityLevel.Zero);
                int widthFractionNumberSecondDigit = Security.BindIntegerInput(tbxWidthFractionSecondDigit.Text, SecurityLevel.Zero);
                double widthFraction = 0.0;
                if (widthFractionNumberSecondDigit > 0)
                {
                    widthFraction = ((double)widthFractionNumberFirstDigit / widthFractionNumberSecondDigit);
                }
                double widthValue = (widthWholeNumberFirstDigit * 10 + widthWholeNumberSecondDigit) + widthFraction;
                string widthUnit = string.Empty;

                int diameterWholeNumberFirstDigit = Security.BindIntegerInput(tbxDiameterWholeFirstDigit.Text, SecurityLevel.Zero);
                int diameterWholeNumberSecondDigit = Security.BindIntegerInput(tbxDiameterWholeSecondDigit.Text, SecurityLevel.Zero);
                int diameterFractionNumberFirstDigit = Security.BindIntegerInput(tbxDiameterFractionFirstDigit.Text, SecurityLevel.Zero);
                int diameterFractionNumberSecondDigit = Security.BindIntegerInput(tbxDiameterFractionSecondDigit.Text, SecurityLevel.Zero);
                double diaFraction = 0.0;
                if (diameterFractionNumberSecondDigit > 0)
                {
                    diaFraction = ((double)diameterFractionNumberFirstDigit / diameterFractionNumberSecondDigit);
                }
                double diameterValue = (diameterWholeNumberFirstDigit * 10 + diameterWholeNumberSecondDigit) + diaFraction;
                string diameterUnit = string.Empty;

                int threadCountWholeNumberFirstDigit = Security.BindIntegerInput(tbxThreadCountWholeFirstDigit.Text, SecurityLevel.Zero);
                int threadCountWholeNumberSecondDigit = Security.BindIntegerInput(tbxThreadCountWholeSecondDigit.Text, SecurityLevel.Zero);
                int threadCountFractionNumberFirstDigit = Security.BindIntegerInput(tbxThreadCountFractionFirstDigit.Text, SecurityLevel.Zero);
                int threadCountFractionNumberSecondDigit = Security.BindIntegerInput(tbxThreadCountFractionSecondDigit.Text, SecurityLevel.Zero);

                double threadFraction = 0.0;
                if (threadCountFractionNumberSecondDigit > 0)
                {
                    threadFraction = ((double)threadCountFractionNumberFirstDigit / threadCountFractionNumberSecondDigit);
                }

                double threadCountValue = (threadCountWholeNumberFirstDigit * 10 + threadCountWholeNumberSecondDigit) + threadFraction;

                string threadCountUnit = string.Empty;

                int lengthWholeNumberFirstDigit = Security.BindIntegerInput(tbxLengthWholeFirstDigit.Text, SecurityLevel.Zero);
                int lengthWholeNumberSecondDigit = Security.BindIntegerInput(tbxLengthWholeSecondDigit.Text, SecurityLevel.Zero);
                int lengthFractionNumberFirstDigit = Security.BindIntegerInput(tbxLengthFractionFirstDigit.Text, SecurityLevel.Zero);
                int lengthFractionNumberSecondDigit = Security.BindIntegerInput(tbxLengthFractionSecondDigit.Text, SecurityLevel.Zero);

                double lengthFraction = 0.0;
                if (lengthFractionNumberSecondDigit > 0)
                {
                    lengthFraction = ((double)lengthFractionNumberFirstDigit / lengthFractionNumberSecondDigit);
                }

                double lengthValue = (lengthWholeNumberFirstDigit * 10 + lengthWholeNumberSecondDigit) + lengthFraction;

                string lengthUnit = string.Empty;

                bool isSpecial = cbxSpecial.Checked;

                try
                {
                    ProductStock stock = new ProductStock(0, size, weight,Convert.ToString(weightoz), widthWholeNumberFirstDigit, widthWholeNumberSecondDigit, widthFractionNumberFirstDigit, widthFractionNumberSecondDigit, widthValue, widthUnit
                       , diameterWholeNumberFirstDigit, diameterWholeNumberSecondDigit, diameterFractionNumberFirstDigit, diameterFractionNumberSecondDigit, diameterValue, diameterUnit
                       , threadCountWholeNumberFirstDigit, threadCountWholeNumberSecondDigit, threadCountFractionNumberFirstDigit, threadCountFractionNumberSecondDigit, threadCountValue, threadCountUnit
                       , lengthWholeNumberFirstDigit, lengthWholeNumberSecondDigit, lengthFractionNumberFirstDigit, lengthFractionNumberSecondDigit, lengthValue, lengthUnit
                       , stockAmount, 0, pkgQuanity, decimalSize);
                    List<ProductStock> stocks = new List<ProductStock>();
                    stocks.Add(stock);

                    //List<ProductStock> stocks = AutoGearSessionManager.TemporaryStocks;

                    //Product newProduct = Product.CreateProduct(name, description, tempImageFolder,
                    //    categoryId, brandId, displayOrder, price, currentCost, standardCost, itemNumber, featuredListing, active, stocks, isSpecial);
                    Product newProduct = Product.CreateProduct(name,name2, description, tempImageFolder,
                        categoryId, displayOrder, price, retailprice, currentCost, additionalPrice, hidTechnicalSpec.Value.Trim(), recipies, additionalinfo, standardCost, cbxSpecial.Checked, itemNumber, featuredListing, active, stocks);

                    TblProduct iProduct = TblProduct.GetTblProductByProductId(newProduct.ProductId);
                    //iProduct.IsClearenceItem = (ddlMetalType.SelectedValue == "0") ? false : true;
                    iProduct.Save();
                    
                    this.CreateAdditionalImageForProduct(newProduct.ProductId);

                    if (newProduct != null)
                    {
                        imgProductDefaultImagePreview.ImageUrl = ImageResizer.CheckImageMissing(newProduct.ProductImageUrl, AutoGear.BLL.SiteSettings.NoImageUrl);
                        imgProductDefaultImagePreview.Visible = true;
                        SaveAllPartnerWithPrice(newProduct.ProductId);
                        uccResponseMessage.SetSuccessMessage(AutoGearCommonMessage.ProductCreateSuccessful);
                    }
                }
                catch (DuplicateException ex)
                {
                    uccResponseMessage.SetFailMessage(ex.Message);
                }
                catch (InvalidOperationException ex)
                {
                    uccResponseMessage.SetFailMessage(ex.Message);
                }

            }
        }
        catch (Exception ex)
        {
            uccResponseMessage.SetFailMessage(AutoGearCommonMessage.ProductCreateFailed);
            uccResponseMessage.Visible = true;
        }
    }

    protected List<string> additionalImages = new List<string>();
    private void CreateAdditionalImageForProduct(int productId)
    {
        //if (fuImageAdditional1.HasFile)
        //    CreateAdditionalImageForProduct(newProduct, fuImageAdditional1, imgPreviewAdditional1, divAdditional1);

        //if (fuImageAdditional2.HasFile) //!divAdditional2.Style["display"].Equals("none") && 
        //    CreateAdditionalImageForProduct(newProduct, fuImageAdditional2, imgPreviewAdditional2, divAdditional2);

        //if (fuImageAdditional3.HasFile) //!divAdditional3.Style["display"].Equals("none") && 
        //    CreateAdditionalImageForProduct(newProduct, fuImageAdditional3, imgPreviewAdditional3, divAdditional3);

        for (int i = 1; i < Request.Files.Count; i++)
        {
            HttpPostedFile fuImageAdditional = Request.Files[i];
            if (fuImageAdditional.ContentLength > 0)
            {
                CreateAdditionalImageForProduct(productId, fuImageAdditional);
            } 
        }

        if (additionalImages.Count > 0)
        {
            rptAdditionalPreview.DataSource = additionalImages;
            rptAdditionalPreview.DataBind();
            divAdditionalPreviews.Visible = true;
        }
    }

    private void CreateAdditionalImageForProduct(int productId, HttpPostedFile fuImageAdditional)
    {
        try
        {
            string tempImagePath = UploadTemporaryAdditionalImageFiles(fuImageAdditional);

            string realImagePath = ProductFileAccessUtility.UploadAdditionalImages(tempImagePath);

            TblProductAdditionalImage additional = new TblProductAdditionalImage();
            additional.ProductID = productId;
            additional.AdditionalImageUrl = realImagePath;
            additional.Save();

            additionalImages.Add(realImagePath);
            //imgPreviewAdditional.ImageUrl = ImageResizer.CheckImageMissing(additional.AdditionalImageUrl, AutoGear.BLL.SiteSettings.NoImageUrl);
            //imgPreviewAdditional.Visible = true;
            //divAdditional.Style["display"] = "block";
        }
        catch (Exception ex)
        {
            throw;
        }
    }

    protected string UploadTemporaryAdditionalImageFiles(HttpPostedFile fuImageAdditional)
    {
        string tempImageFolder = string.Empty;
        if (fuImageAdditional.ContentLength > 0)
        {
            tempImageFolder = SiteUtility.TempFolder + fuImageAdditional.FileName;

            if (File.Exists(MapPath(tempImageFolder)))
                FileAccessUtility.DeleteFile(tempImageFolder);

            string contentType = fuImageAdditional.ContentType.ToLower();
            if (contentType == "image/jpg" || contentType == "image/gif" || contentType == "image/png"
                || contentType == "image/jpeg" || contentType == "image/bmp" || contentType == "image/pjpeg"
                || contentType == "image/x-png")
            {
                fuImageAdditional.SaveAs(MapPath(tempImageFolder));
            }
        }

        return tempImageFolder;
    }

    protected void LoadDropDowns()
    {
        //ddlBrand.DataSource = ProductBrand.Brands(false);
        //ddlBrand.DataTextField = "BrandName";
        //ddlBrand.DataValueField = "ProductBrandId";
        //ddlBrand.DataBind();

        ddlParent.Items.Clear();
        ReadWriteCustomCollection<KeyValuePair<string, string>> productCategoryTree = CategoryManager.GetSubCategoryTree(SiteUtility.SuperRootCategoryId);
        foreach (KeyValuePair<string, string> productCategory in productCategoryTree)
        {
            ddlParent.Items.Add(new ListItem(productCategory.Key,Server.HtmlDecode(productCategory.Value)));
        }
    }

    protected string UploadTemporaryFiles()
    {
        string tempImageFolder = string.Empty;
        if (fluProductDefaultImage.HasFile)
        {
            tempImageFolder = SiteUtility.TempFolder + fluProductDefaultImage.FileName;

            if (File.Exists(MapPath(tempImageFolder)))
                FileAccessUtility.DeleteFile(tempImageFolder);

            string contentType = fluProductDefaultImage.PostedFile.ContentType.ToLower();
            if (contentType == "image/jpg" || contentType == "image/gif" || contentType == "image/png"
                || contentType == "image/jpeg" || contentType == "image/bmp" || contentType == "image/pjpeg"
                || contentType == "image/x-png")
            {
                fluProductDefaultImage.SaveAs(MapPath(tempImageFolder));
            }

        }
        return tempImageFolder;
    }
    protected void btnExportImport_Click(object sender, EventArgs e)
    {
        Response.Redirect(AutoGear.BLL.CustomSiteMap.ExportImport);
    }

    protected void lnbAddNew_Click(object sender, EventArgs e)
    {
        ProductPartner newProd = new ProductPartner();
        newProd.BrandName = "";
        newProd.PartnerId = 1;
        newProd.PartnerProductId = -1;
        partnerProducts.Add(newProd);
        repProductPartners.DataSource = partnerProducts;
        repProductPartners.DataBind();

    }
    protected void repProductPartners_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            ProductPartner newProd = e.Item.DataItem as ProductPartner;
            DropDownList ddlBrandName = e.Item.FindControl("ddlBrandName") as DropDownList;
            ddlBrandName.DataSource = brands;
            ddlBrandName.DataTextField = "BrandName";
            ddlBrandName.DataValueField = "ProductBrandId";
            ddlBrandName.DataBind();

        }
    }

    private void SaveAllPartnerWithPrice(Int32 productId)
    {
        foreach (RepeaterItem item in repProductPartners.Items)
        {

            HtmlInputHidden hidProdPartnerId = item.FindControl("hidProdPartnerId") as HtmlInputHidden;
            DropDownList ddlBrandName = item.FindControl("ddlBrandName") as DropDownList;
            TextBox txtProductionCost = item.FindControl("txtProductionCost") as TextBox;
            TextBox txtSellPrice = item.FindControl("txtSellPrice") as TextBox;
            TblPartnerProduct partnerProduct = new TblPartnerProduct();
            partnerProduct.ProductId = productId;
            partnerProduct.ProductionCost = Convert.ToDecimal(txtProductionCost.Text.Trim());
            partnerProduct.PartnerId = Convert.ToInt32(ddlBrandName.SelectedItem.Value);
            partnerProduct.ProductionCost = Convert.ToDecimal(txtProductionCost.Text.Trim());
            partnerProduct.SellPrice = Convert.ToDecimal(txtSellPrice.Text.Trim());
            partnerProduct.Save();
        }
    }
}
